<!--
  * 内部费用单
  *
-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-card size="small" :bordered="false" :hoverable="false" class="query-form-wrapper smart-margin-bottom10 smart-radius-2">
    <a-form>
      <a-row :gutter="[8, 10]">
        <a-col :span="5.5">
          <a-form-item label="单据日期" class="smart-margin-bottom0">
            <a-date-picker v-model:value="form.bill_date" valueFormat="YYYY-MM-DD" />
          </a-form-item>
        </a-col>
        <a-col :span="3">
          <a-form-item label="员工" class="smart-margin-bottom0">
            <a-cascader v-model:value="form.related_user_id" :options="options" :load-data="loadData" placeholder="员工名称" change-on-select />
          </a-form-item>
        </a-col>

        <a-col :span="5">
          <a-button-group>
            <a-button type="primary" html-type="submit" @click="onSearch" v-privilege="'goods:query'">
              <template #icon>
                <SearchOutlined />
              </template>
              查询
            </a-button>
            <a-button @click="resetQueryData" v-privilege="'goods:query'">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
          </a-button-group>
        </a-col>
      </a-row>
    </a-form>
  </a-card>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true" class="query-table-wrapper">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button @click="addGoods" type="primary" v-privilege="'goods:add'">
          <template #icon>
            <PlusOutlined />
          </template>
          新建
        </a-button>

        <a-button @click="onExport" type="primary" v-privilege="'driver:export'">
          <template #icon>
            <ExportOutlined />
          </template>
          导出
        </a-button>
      </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.ERP.GOODS" :refresh="queryData" />
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->
    <div class="table-wrapper">
      <a-table size="small" :dataSource="tableData" :columns="columns" rowKey="id" bordered :scroll="{ x: 'max-content', y: tableScrollY }" :pagination="false" :showSorterTooltip="false" :loading="tableLoading" :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }">
        <template #bodyCell="{ text, record, column }">
          <template v-if="column.dataIndex === 'bill_number'">
            <a @click="detail(record)">{{ text }}</a>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <div class="smart-table-operate">
              <a-button @click="detail(record)" type="link" style="color: #97999c">详情</a-button>
              <a-button @click="addGoods(record)" type="link" v-privilege="'driver:edit'">编辑</a-button>
              <a-button @click="deleteData(record.id, record.bill_number)" danger type="link" v-privilege="'driver:del'">删除</a-button>
            </div>
          </template>
        </template>
        <template #summary>
          <a-table-summary>
            <a-table-summary-row>
              <a-table-summary-cell :index="0">总计</a-table-summary-cell>
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell>
                <a-typography-text type="danger">{{ Number(sum).toFixed(2) }}</a-typography-text>
              </a-table-summary-cell>
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell :index="columns.length" />
            </a-table-summary-row>
          </a-table-summary>
        </template>
      </a-table>
    </div>

    <div class="smart-query-table-page query-table-page">
      <a-pagination showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS" :defaultPageSize="queryForm.limit" v-model:current="queryForm.page" v-model:pageSize="queryForm.limit" :total="total" @change="queryData" @showSizeChange="queryData" :show-total="() => `共${total}条`" />
    </div>

    <CostFormModal ref="formModal" @reload-list="queryData" />
    <!---------- 详情 begin ----------->
    <CostDetailsModal ref="detailRef" />
    <!---------- 详情 end ----------->
  </a-card>
</template>
<script setup lang="ts">
import CostDetailsModal from './components/cost-details-modal.vue'
import CostFormModal from './components/cost-form-modal.vue'
import { searchApi } from '@/api/search/search-api'
import { expenseApi } from '@/api/business/finance/cost-api'
import TableOperator from '@/components/support/table-operator/index.vue'
import { useQuery } from '@/hooks/web/use-query-hook'
import { PAGE_SIZE_OPTIONS } from '@/constants/system/common-const'
import { TABLE_ID_CONST } from '@/constants/support/table-id-const'
import { useResize } from '@/hooks/web/use-resize-hook'
import { useUserStore } from '@/store/modules/user-store'
const { getUserInfo } = useUserStore()
const userInfo = getUserInfo
// ----------------------------- 计算表格高度 -----------------------------
const { tableScrollY } = useResize()

// ---------------------------- 表格列 ----------------------------

const columns = ref([
  {
    title: '单据编号',
    dataIndex: 'bill_number',
    width: 180
  },
  {
    title: '员工',
    dataIndex: 'related_user_name'
  },
  {
    title: '单据日期',
    dataIndex: 'bill_date'
  },
  {
    title: '制单时间',
    dataIndex: 'create_time'
  },
  {
    title: '费用金额(元)',
    dataIndex: 'total_amount'
  },
  {
    title: '制单人',
    dataIndex: 'dealerName'
  },
  {
    title: '费用备注',
    dataIndex: 'remark'
  },
  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
    width: 100
  }
])

// ---------------------------- 查询数据表单和方法 ----------------------------
const options = ref([
  {
    value: 1,
    label: '业务员',
    isLeaf: false
  },
  {
    value: 2,
    label: '用户',
    isLeaf: false
  }
])
const form = ref({
  bill_date: '',
  related_user_id: []
})
const sum = ref('')
const { queryForm, queryFormOp, tableData, tableLoading, total, resetQuery, onSearch, queryData, deleteData } = useQuery({
  fetchDataApi: async (params) => {
    const data = {
      ...params,
      bill_date: form.value.bill_date,
      related_user_type: form.value.related_user_id[0],
      related_user_id: form.value.related_user_id[1]
    }
    const res = await expenseApi.queryExpenseList(data)
    sum.value = res.data.sum
    return {
      list: res.data.data,
      total: res.data.total
    }
  },
  fetchDeleteApi: async (id) => {
    const res = await expenseApi.delExpense({ id })
    return !!res
  },
  queryFormFilter: {},
  queryFormOp: {}
})
onMounted(queryData)

const resetQueryData = () => {
  form.value.bill_date = ''
  form.value.related_user_id = []
  resetQuery()
}

// 选择表格行
const selectedRowKeyList = ref([])

function onSelectChange(selectedRowKeys) {
  selectedRowKeyList.value = selectedRowKeys
}

const loadData = (selectedOptions) => {
  const targetOption = selectedOptions[selectedOptions.length - 1]
  targetOption.loading = true
  setTimeout(async () => {
    // 根据二级选项的值调用不同的接口
    if (targetOption.value === 1) {
      // 调用业务员相关的接口
      const res = await searchApi.salesmanList()
      options.value[0].children = res.data.map((val) => {
        return {
          value: val.id,
          label: val.rename
        }
      })
      targetOption.loading = false
    } else if (targetOption.value === 2) {
      options.value[1].children = [
        {
          value: userInfo.id,
          label: userInfo.username
        }
      ]
      targetOption.loading = false
    }
  }, 500)
}

// ---------------------------- 添加/修改 ----------------------------
const formModal = ref()

async function addGoods(goodsData) {
  if (goodsData.id) {
    const res = await expenseApi.detailExpense({ id: goodsData.id })
    formModal.value.showDrawer(res.data)
  } else {
    formModal.value.showDrawer(goodsData)
  }
}

// ---------------------------- 详情 ----------------------------
const detailRef = ref()

const detail = async (goodsData) => {
  if (goodsData.id) {
    const res = await expenseApi.detailExpense({ id: goodsData.id })
    detailRef.value.showDrawer(res.data)
  } else {
    detailRef.value.showDrawer(goodsData)
  }
}
// ---------------------------- 导出 ----------------------------
function onExport() {
  const data = {
    bill_date: form.value.bill_date,
    related_user_type: form.value.related_user_id[0],
    related_user_id: form.value.related_user_id[1]
  }
  expenseApi.exportExpense(data)
}
</script>
